package com.lcf.jwt.controller;

import cn.hutool.core.util.IdUtil;
import com.lcf.jwt.entity.AuthInfo;
import com.lcf.jwt.entity.AuthUser;
import com.lcf.jwt.entity.ImgResult;
import com.lcf.jwt.entity.JwtUser;
import com.lcf.jwt.mapper.JwtUserMapper;
import com.lcf.jwt.service.JwtUserDetailsService;
import com.lcf.jwt.utils.EncryptUtils;
import com.lcf.jwt.utils.JwtTokenUtil;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountExpiredException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private JwtUserMapper jwtUserMapper;

    @Value("${jwt.header}")
    private String tokenHeader;


    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Value("${jwt.codeKey}")
    private String codeKey;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(value = "/login")
    public ResponseEntity login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request, HttpServletResponse response) throws Exception {

        JwtUser jwtUser = jwtUserMapper.findUserByName(authUser.getUsername());
        if (!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(authUser.getPassword()))) {
            throw new AccountExpiredException("密码错误");
        }

        if (!jwtUser.isEnabled()) {
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }
        // 生成令牌
        final String token = jwtTokenUtil.generateToken(jwtUser.getUsername());
        response.setHeader(tokenHeader, token);
        response.setHeader("foo", "123");
        // 返回 token
        return ResponseEntity.ok(new AuthInfo(token, jwtUser));

    }

    @GetMapping(value = "/info/{name}")
    public ResponseEntity getUserInfo(@PathVariable String name) {
        JwtUser jwtUser = jwtUserDetailsService.loadUserByUsername(name);
        return ResponseEntity.ok(jwtUser);
    }

    @GetMapping(value = "/code")
    public ImgResult getCode() {
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果：5
        String result = captcha.text();
        String uuid = codeKey + IdUtil.simpleUUID();
//        redisService.saveCode(uuid,result);
        return new ImgResult(captcha.toBase64(), uuid);
    }
}
